﻿using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;

namespace Yeti_v0._01.App_code
{
    public class SharedDbFunctions
    {




        public static Topic GetTopicByPatternContent(string patternContent)
        {
            List<Topic> topics;

            #region Querying_with_object_services
            ////Querying with Object Services and Entity SQL
            //using (var ctx = new yetiEntities())
            //{
            //    string sqlString = "SELECT VALUE topic FROM yetiEntities.Topics AS topic ,yetiEntities.Patterns AS pattern   WHERE topic.ID_topic == pattern.ID_topic and pattern.Content =  " + patternContent;
            //    ObjectQuery<Topic> topics = ctx.CreateQuery<Topic>(sqlString);
            //    return topics.FirstOrDefault();
            //}
#endregion
            

            //Querying with native sql            
            using (yetiEntities ctx = new yetiEntities())
            {              
                 topics = ctx.ExecuteStoreQuery<Topic>("select * from Topic t, Pattern p where p.Content = '" + patternContent + "' and t.ID_topic = p.ID_topic", null).ToList();
            }

            //nie znaleziono topicu - ustawiamy domyslny
            if (!topics.Any())
            {
                using (yetiEntities ctx = new yetiEntities())
                {
                    topics = ctx.ExecuteStoreQuery<Topic>("select * from Topic t where t.Name = 'NIEZDEFINIOWANY' ", null).ToList();
                }
            }

            return topics.FirstOrDefault();


        }
    }
}